package com.youlai.boot.modules.collect.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.modules.collect.mapper.CollectMapper;
import com.youlai.boot.modules.collect.service.CollectService;
import com.youlai.boot.modules.collect.model.entity.Collect;
import com.youlai.boot.modules.collect.model.form.CollectForm;
import com.youlai.boot.modules.collect.model.query.CollectQuery;
import com.youlai.boot.modules.collect.model.vo.CollectVO;
import com.youlai.boot.modules.collect.converter.CollectConverter;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

import com.youlai.boot.core.security.util.SecurityUtils;

/**
 * 用户收藏服务实现类
 *
 * @author maoyu
 * @since 2025-02-27 10:29
 */
@Service
@RequiredArgsConstructor
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {

    private final CollectConverter collectConverter;

    /**
    * 获取用户收藏分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<CollectVO>} 用户收藏分页列表
    */
    @Override
    public IPage<CollectVO> getCollectPage(CollectQuery queryParams) {
        Page<CollectVO> pageVO = this.baseMapper.getCollectPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取用户收藏表单数据
     *
     * @param id 用户收藏ID
     * @return
     */
    @Override
    public CollectForm getCollectFormData(Long id) {
        Collect entity = this.getById(id);
        return collectConverter.toForm(entity);
    }
    
    /**
     * 新增用户收藏
     *
     * @param formData 用户收藏表单对象
     * @return
     */
    @Override
    public CollectVO saveCollect(CollectForm formData) {
        Collect entity = collectConverter.toEntity(formData);
        entity.setUserId(SecurityUtils.getUserId());
        
        this.save(entity);

        return collectConverter.toCollectVO(entity);
    }
    
    /**
     * 更新用户收藏
     *
     * @param id   用户收藏ID
     * @param formData 用户收藏表单对象
     * @return
     */
    @Override
    public boolean updateCollect(Long id,CollectForm formData) {
        Collect entity = collectConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除用户收藏
     *
     * @param ids 用户收藏ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteCollects(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的用户收藏数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
